package com.xjrsoft.common.runner;

import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.db.PageResult;
import cn.hutool.db.SqlConnRunner;
import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.handler.NumberHandler;
import cn.hutool.db.handler.PageResultHandler;
import cn.hutool.db.sql.SqlBuilder;

import java.sql.Connection;
import java.sql.SQLException;

public class XjrSqlConnRunner extends SqlConnRunner {
    public XjrSqlConnRunner(Dialect dialect) {
        super(dialect);
    }

    public long count(Connection conn, SqlBuilder sqlBuilder) throws SQLException {
        SqlBuilder countSqlBuilder = SqlBuilder.of(sqlBuilder.build());
        countSqlBuilder.insertPreFragment("SELECT count(1) from(").append(") t");
        countSqlBuilder.addParams(sqlBuilder.getParamValueArray());
        return (long)((Number)this.page(conn, countSqlBuilder, (Page)null, new NumberHandler())).intValue();
    }

    @Override
    public PageResult<Entity> page(Connection conn, SqlBuilder sqlBuilder, Page page) throws SQLException {
        PageResultHandler pageResultHandler = new PageResultHandler(new PageResult(page.getPageNumber(), page.getPageSize(), (int)this.count(conn, sqlBuilder)), this.caseInsensitive);
        return (PageResult)this.page(conn, sqlBuilder, page, pageResultHandler);
    }
}
